//
//  NKFindViewController.m
//  NewKY
//
//  Created by Dee on 2016/11/13.
//  Copyright © 2016年 Dee. All rights reserved.
//

#import "NKFindViewController.h"
#import <Masonry.h>
#import <AFNetworking.h>
#import "NKFindDetailViewController.h"
#import "NetWorkingManager.h"
#import "NKFindTableViewCell.h"
#import <MJRefresh.h>
#import <SVProgressHUD.h>

@interface NKFindViewController () <UITableViewDelegate,UITableViewDataSource>

/** 属性tableView */
@property (nonatomic,weak) UITableView *findTableView;

/** 数据源数组 */
@property (nonatomic,strong) NSMutableArray *infoList;

@end

@implementation NKFindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数据源数组
    self.infoList = [NSMutableArray array];
    //加载网络数据
    [self loadData];
    
    self.navigationItem.title = @"关注医生";
    
    //创建tableView
    UITableView *findTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];

    //设置背景颜色,调试
//    findTableView.backgroundColor = [UIColor redColor];
    self.findTableView = findTableView;
    //添加到父视图上
    [self.view addSubview:findTableView];
    
    //设置约束
    [findTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    //设置数据源对象
    findTableView.dataSource = self;
    
    //设置代理对象
    findTableView.delegate = self;
    
    //注册cell
    UINib *nib = [UINib nibWithNibName:@"NKFindTableViewCell" bundle:nil];
    [findTableView registerNib:nib forCellReuseIdentifier:@"FindCell"];
    
    //================== 上下拉刷新 =================//
    findTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(netRequest)];
    findTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(netRequest)];
    
    //设置弹框的属性
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    
    
    
}

//加载刷新的数据
- (void)netRequest{
    
    //根据不同的类型选择不同的接口
    NSString *URLStr = @"";
    NSDictionary *parameters = [[NSDictionary alloc] init];
    
    URLStr = @"http://iosapi.itcast.cn/doctor/doctorList.json.php";
    parameters = @{@"user_id":@(1000089),@"page_size":@(15),@"page":@(2)};
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    //显示遮罩层
    [SVProgressHUD setInfoImage:[UIImage imageNamed:@"0"]];
    [SVProgressHUD showInfoWithStatus:@"正在加载医生列表..."];
    
    [NetWorkingManager sendPOSTDataWithPath:URLStr withParamters:parameters withProgress:^(float progress) {
        
    } success:^(BOOL isSuccess, id responseObject) {
        
        if ([responseObject isKindOfClass:[NSError class]]) {
            [SVProgressHUD showErrorWithStatus:@"您的网络不给力"];
            [self.findTableView.mj_header endRefreshing];
            [self.findTableView.mj_footer endRefreshing];
            return ;
        }
        //字典转模型
        NSArray *dictArr = responseObject[@"data"];
        NSArray *arr = [NSArray modelArrayWithClass:[NKFindModel class] json:dictArr];
        
        [self.infoList addObjectsFromArray:arr];
        
        //刷新数组
        [self.findTableView reloadData];
        [SVProgressHUD showSuccessWithStatus:@"加载成功"];
        
        [self.findTableView.mj_header endRefreshing];
        [self.findTableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        if (error != nil) {
            NSLog(@"%@",error);
        }
    }];
}

/**
 加载数据
 */
- (void)loadData{
    
    //发送POST请求,获取数据
    [NetWorkingManager sendPOSTDataWithPath:@"http://iosapi.itcast.cn/doctor/doctorList.json.php" withParamters:@{@"user_id":@1000089,@"page_size":@15,@"page":@1} withProgress:^(float progress) {
        //弹框,正在加载网络数据
//        [SVProgressHUD setInfoImage:[UIImage imageNamed:@"0"]];
//        [SVProgressHUD showProgress:progress status:@"正在加载医生列表..."];
    } success:^(BOOL isSuccess, id responseObject) {
        //responseObject : 返回的是一个字典
        //取出字典里面的字典数组
        NSArray *dictArr = responseObject[@"data"];
        //字典转模
        NSArray *arr = [NSArray modelArrayWithClass:[NKFindModel class] json:dictArr];
        [self.infoList addObjectsFromArray:arr];
        //弹框
        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.5];
//        [SVProgressHUD showSuccessWithStatus:@"加载成功"];
        //回到主线程刷新数据
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self.findTableView reloadData];
        }];
    } failure:^(NSError *error) {
        if (error != nil) {
            [SVProgressHUD showErrorWithStatus:@"网络出错正在重新加载..."];
            //重新加载数据
            [self loadData];
        }
    }];
}

- (void)delayMethod{
    
    [SVProgressHUD showSuccessWithStatus:@"加载成功"];
}


#pragma mark - 实现数据源方法
//返回多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.infoList.count;
}

//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NKFindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FindCell" forIndexPath:indexPath];
    //取出模型数据
    NKFindModel *model = self.infoList[indexPath.row];
    cell.model = model;
    return cell;
}

/**
 设置行高
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}


/**
 点击对应的cell,跳转到详情医生控制器

 @param tableView 点击的tableView
 @param indexPath 点击tableView哪一行的cell
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NKFindDetailViewController *findDetailVC = [[NKFindDetailViewController alloc] init];
    NKFindModel *model = self.infoList[indexPath.row];
    findDetailVC.detailModel = model;
    
    void(^completion)(NKFindModel *,BOOL) = ^(NKFindModel *model,BOOL isAttention){
        if (isAttention == YES) {
            [self.infoList addObject:model];
        }else{
            [self.infoList removeObject:model];
        }
        
        [self.findTableView reloadData];
    };
    findDetailVC.completion = completion;
    
    [self.navigationController pushViewController:findDetailVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
